<?php
/*
 * filename: mysql.php
 * author: xuguoyu
 * date: 2010/4/21
 * update:
 * description: 
 */

class Mysql
{
	var $DBConn; //数据库连接
	var $DBName; //数据库名

	function Mysql()
	{
		//类初始化
		$this->DBConn = "";
		$this->DBName = "";
	}

	//连接服务器
	function connect($host,$user,$pwd)
	{
		$conn = @mysql_connect($host,$user,$pwd); //连接mysql
		if (!$conn)
		{
			$this->errMsg("连接数据库失败!\n".mysql_error());
		}
		else
		{
			$this->DBConn = $conn; //暂存数据库连接
		}
	}

	//选定数据库
	function selectDb($db_name)
	{
		$this->DBName = $db_name;
		if (!mysql_select_db($db_name,$this->DBConn))
		{
			$this->errMsg("选定数据库[{$db_name}]失败!");
		}
	}

	//执行查询
	function query($sql,$Type = MYSQL_BOTH) //MYSQL_BOTH, MYSQL_ASSOC, MYSQL_NUM
	{
		if (empty($sql))
			$this->errMsg("未指定查询语句!");

		$result = @mysql_query($sql);
		if (!$result)
		{
			global $CFG;
			if(isset($CFG["db"]["err_log"]))
			{
				$err_log = $CFG["db"]["err_log"];
				$err_log_file = $CFG["db"]["err_log_file"];

				if($err_log)
				{
					$fh = @fopen($err_log_file, "a+");
					if($fh)
					{
						fwrite($fh, "src: {$_SERVER['REQUEST_URI']}\nsql: {$sql}\n".mysql_error()."\n".date("Y-m-d H:i:s")."\n\n");
						fclose($fh);
					}
					else
					{
						echo "can not write sql err_log.\n<br/>";
					}
				}
			}
			$this->errMsg("执行查询出错:\n<br/>SQL: {$sql}\n<br/>".mysql_error());
		}
		else
		{
			if (preg_match("/^\(?select/isU",$sql))
			{
				$re_arr = array();
				while($re_rs = mysql_fetch_array($result,$Type))
				{
					$re_arr[] = $re_rs;
				}
				mysql_free_result($result);
				return $re_arr;
			}
			return true;
		}
	}

	//取最后一次insert的记录id
	function insertId()
	{
        return mysql_insert_id();
    }

	//取最后一次执行语句影响的记录数
	function processNum($dbconn = null)
	{
		if($dbconn==null) $dbconn = $this->DBConn;
		return mysql_affected_rows($dbconn);
	}

	//释放数据库连接
	function close()
	{
		mysql_close($this->DBConn);
	}

	//显示错误信息
	function errMsg($msg)
	{
		global $CFG;
		if(isset($CFG["err"]))
		{
			switch($CFG["err"]["mode"])
			{
				case 1:
					header("Location: {$CFG['err']['page']}");
					die();
					break;

				case 2:
					return;
					break;
			}
		}

		die("<style>body{font-size:12px;}</style><br/><font color=red>Mysql class 错误:</font><hr size=1 color=#0099ff>来源: {$_SERVER['REQUEST_URI']}<br/>信息: {$msg}");
	}
}

/*
$db = new mysql();
$db->connect("192.168.0.193","sa","123"); //连接mysql
$db->selectDb("zdl");

$rs = $db->query("select * from member");
if(!empty($rs))
{
	foreach($rs as $v)
	{
		echo "data:[".$v["username"]."]<br/>";
	}
}
$db->close();
//*/
?>